package com.qf.base.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author 30909
 * 图片的工具类
 */
public class ImageUtil {

    public static BufferedImage zoom(BufferedImage sourceImage, int width, int height) {
        //放缩图片
        Image image = sourceImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        //做出一个空白的图片来
        BufferedImage zoomImage = new BufferedImage(width, height, sourceImage.getType());
        //把目标设置为空白
        //Color 类使用一个int值来表达一个颜色
        //由高八位，次八位，第八位，顺次表达  透明度、红、绿、蓝
        Graphics graphics = zoomImage.getGraphics();


        //绘制图片信息
        graphics.setColor(new Color(0xffffff));

        return zoomImage;
    }

    /**
     * 图片缩放
     */
    public static String zoom(String sourcePath, String targetPath, int width, int height) {
        //获取文件格式
        String format = sourcePath.substring(sourcePath.lastIndexOf(".") + 1);
        //获取原图片文件的图片对象
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(new File(sourcePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //放缩
        Image image = bufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        //做出一个空白的图片来
        BufferedImage zoomImage = new BufferedImage(width, height, bufferedImage.getType());


        //把目标设置为空白
        Graphics graphics = zoomImage.getGraphics();
        //设置颜色
        // Color 类使用一个 int 值来表达一个颜色
        // 由高八位，次高八位，次八位，低八位，来表达 透明度、红、绿、蓝
        graphics.setColor(new Color(0xffffff));

        //绘制图片信息
        graphics.drawImage(image, 0, 0, null);

        //保存文件
        try {
            ImageIO.write(zoomImage, format, new File(targetPath));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return targetPath;
    }

    /**
     * 在右下角添加作者水印的方法
     * @param sourceImage   原图片
     * @param markSting  添加水印的文本
     * @return      带水印的图片
     */
    public static BufferedImage markOn(BufferedImage sourceImage ,String markSting){
        //获取图片上画布
        Graphics graphics = sourceImage.getGraphics();

        //设置画布的颜色
        graphics.setColor(new Color(0xCDCDCD));
        graphics.setFont(new Font("宋体", Font.BOLD, 30));
        int stringWidth = graphics.getFontMetrics().stringWidth(markSting);
        int stringHeight = (int) (0.22*graphics.getFontMetrics().getHeight());
        graphics.drawString(markSting, sourceImage.getWidth()-stringHeight-stringWidth,
                sourceImage.getHeight()-stringHeight);

        return sourceImage;
    }


    /**
     * 测试方法
     * @param args
     */
    public static void main(String[] args) {
        zoom("C:\\face\\1.jpg","C:\\face\\a.jpg", 150, 150);
    }
}
